package vip.xiaonuo.modular.manage.tsdatarecord.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.TreeBuildFactory;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseDataFolder;
import vip.xiaonuo.modular.manage.tsdatarecord.entity.BaseDataRecord;
import vip.xiaonuo.modular.manage.tsdatarecord.enums.TimeSpaceDataRecordExceptionEnum;
import vip.xiaonuo.modular.manage.tsdatarecord.mapper.BaseDataFolderMapper;
import vip.xiaonuo.modular.manage.tsdatarecord.service.BaseDataFolderService;
import vip.xiaonuo.modular.manage.tsdatarecord.service.BaseDataRecordService;

import java.util.List;

/**
 * BaseDataFolderServiceImpl
 *
 * @author JackLee
 * 2022/8/11 15:25
 */
@Service
public class BaseDataFolderServiceImpl extends ServiceImpl<BaseDataFolderMapper, BaseDataFolder> implements BaseDataFolderService {
    @Autowired
    private BaseDataRecordService baseDataRecordService;

    @Override
    public BaseDataFolder add(BaseDataFolder folder) {
        this.save(folder);
        return folder;
    }

    @Override
    public void edit(BaseDataFolder folder) {
        BaseDataFolder f = this.getById(folder.getId());
        if (ObjectUtil.isNull(f))
            throw new ServiceException(TimeSpaceDataRecordExceptionEnum.NOT_EXIST);
        this.updateById(folder);
    }

    @Override
    public void delete(BaseDataFolder folder) {
        QueryWrapper<BaseDataFolder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BaseDataFolder::getPid, folder.getId());
        int childSize = this.count(queryWrapper);
        if (childSize > 0) {
            throw new ServiceException(TimeSpaceDataRecordExceptionEnum.HAS_CHILD);
        }

        QueryWrapper<BaseDataRecord> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.lambda().eq(BaseDataRecord::getFolderId, folder.getId());
        int recordSize = baseDataRecordService.count(recordQueryWrapper);
        if (recordSize > 0) {
            throw new ServiceException(TimeSpaceDataRecordExceptionEnum.HAS_CHILD);
        }

        this.removeById(folder);
    }

    @Override
    public List<BaseDataFolder> buildTree() {
        QueryWrapper<BaseDataFolder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(BaseDataFolder::getPid).orderByAsc(BaseDataFolder::getSortNum);
         return new TreeBuildFactory<BaseDataFolder>().doTreeBuild(this.list(queryWrapper));
    }
}
